package com.young.trigger.handler;



import com.young.core.domain.JobDO;
import com.young.core.domain.NodeDO;

import java.util.List;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;


public class HttpRequest implements Delayed {

    protected transient JobDO job;
    private transient NodeDO node;
    protected transient List<NodeDO> candidateNodes;

    protected String traceId;
    protected int total = 1;
    protected int index;
    protected long ts;

    private long et = System.currentTimeMillis();
    protected transient int retryTimes = 0;

    private transient int ni = 0;
    public int getRetryTimes() {
        return retryTimes;
    }

    public void retry() {
        retry(1,TimeUnit.SECONDS);
    }

    public void retry(long delayTime, TimeUnit timeUnit) {
        this.retryTimes++;
        node = candidateNodes.get((++ni) % candidateNodes.size());
        delay(delayTime, timeUnit);
    }

    public NodeDO selected() {
        if (node == null) {
            node = candidateNodes.get(ni);
        }
        return node;
    }

    /**
     * @param time 毫秒
     */
    public void delay(long time) {
        et = System.currentTimeMillis() + time;
    }

    public void delay(long time, TimeUnit unit) {
        et = System.currentTimeMillis() + unit.toMillis(time);
    }

    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(et - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }

    @Override
    public int compareTo(Delayed other) {
        if (other == this) {
            return 0;
        }
        long d = (getDelay(TimeUnit.MILLISECONDS) -
                other.getDelay(TimeUnit.MILLISECONDS));
        return (d == 0) ? 0 : ((d < 0) ? -1 : 1);
    }

}
